//
//  AppDelegate.m
//  gdemm
//
//  Created by 乔明超 on 16/9/27.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "AppDelegate.h"
#import <Bugly/Bugly.h>
#import <Bugout/Bugout.h>
#import <PgyUpdate/PgyUpdateManager.h>
#import "LoginController.h"
#import "SliderController.h"
#import "PolicyManager.h"
#import "FastTaskManager.h"
#import "AutoLogin.h"
#import "IQKeyboardManager/IQKeyboardManager.h"
#import "KeyChain.h"
#import "SoftwareInfo.h"
#import "BrowserCommit.h"
#import "DeviceInfo.h"
#import "CADViewer.h"
#import "HeartBeat.h"
@interface AppDelegate ()
{
    dispatch_source_t _timer;
}
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [CADViewer InitCADViewer]; // 图纸浏览驱动初始化
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    // Override point for customization after application launch.
    
    //初始化BugOut
    [Bugout init:@"530954041e37e813d3d849d96be1bb3d" channel:@"channel" config:[BugoutConfig defaultConfig]];
    
    //初始化更新检查SDK
    [[PgyUpdateManager sharedPgyManager] startManagerWithAppId:@"48b7620d4cbcd3afb503d34fb633d39c"];
    [[PgyUpdateManager sharedPgyManager] checkUpdate];
    //初始化Bugly
    [Bugly startWithAppId:@"bba25feb33"];
    //注册远程通知
    if ([UIDevice currentDevice].systemVersion.doubleValue <= 8.0) {
        // 当系统版本<=8.0
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        UIRemoteNotificationType type = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert;
        [application registerForRemoteNotificationTypes:type];
#pragma clang diagnostic pop
        
    }else
    {
        // 当系统版本>=8.0
        UIUserNotificationType type = UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
        // 注册通知类型
        [application registerUserNotificationSettings:settings];
        // 申请试用通知
        [application registerForRemoteNotifications];
    }
    //保存设备唯一标识符
    NSMutableDictionary *uuidDict = (NSMutableDictionary *)[KeyChain load:KEY_SERVICENAME];
    NSString *uuidStr = uuidDict[KEY_UUID];
    if (uuidStr == nil) {
        NSString *uuid = [[NSUUID UUID]UUIDString];
        NSMutableDictionary *uuidDic = [NSMutableDictionary dictionary];
        [uuidDic setObject:uuid forKey:KEY_UUID];
        [KeyChain save:KEY_SERVICENAME data:uuidDic];
        
        HRLog(@"uuid ============ %@",uuid);
    }
    //[KeyChain delete:KEY_SERVICENAME];
    HRLog(@"uuidStr =============== %@",uuidStr);
    
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    keyboardManager.enable = YES;
    keyboardManager.shouldResignOnTouchOutside = YES;
    //设置window
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //申请注册通知类型
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {
        UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
        // 注册通知类型
        [application registerUserNotificationSettings:settings];
    }
    
    //开启策略更新
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[BrowserCommit shareInstance]commitHistory];
        [FastTaskManager getInstance];
        [PolicyManager getInstance];
    });
    
    //提交软件信息
    //间隔时间 : 10分钟提交一次
    uint64_t interval = 600 * NSEC_PER_SEC;
    //创建一个专门执行timer回调的GCD队列
    dispatch_queue_t queue = dispatch_queue_create("softInfo", 0);
    //创建Timer
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //使用dispatch_source_set_timer函数设置timer参数
    
    dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, 300 * NSEC_PER_SEC), interval, 0);
    //设置回调
    
    dispatch_source_set_event_handler(_timer, ^{
        [[BrowserCommit shareInstance]commitHistory];
        [[SoftwareInfo getInstance]commitSoftInfo];
    });
    //dispatch_source默认是Suspend，通过dispatch_resume函数开始它
    dispatch_resume(_timer);
    
    //判断是否自动登录 设置根控制器
    if ([AutoLogin autoLogin]) {
        
        SliderController *sliderVC = [[SliderController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:sliderVC];
        
        self.window.rootViewController = nav;
    }else{
        LoginController *loginVC = [[LoginController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
        self.window.rootViewController = nav;
    }
    //显示窗口
    [self.window makeKeyAndVisible];
    
    return YES;
}

/**
 *  获取到用户对应当前应用程序的deviceToken时就会调用
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // <47e58207 31340f18 ed83ba54 f999641a 3d68bc7b f3e2db29 953188ec 7d0cecfb>
    //HRLog(@"%@", deviceToken);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
        
    }];
    //开启策略更新
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [FastTaskManager getInstance];
        [PolicyManager getInstance];
    });
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [[HeartBeat shareInstance]offline];
    [CADViewer UninitCADViewer];// 释放图纸浏览驱动
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
